// 引入SDK核心类
var QQMapWX = require('../../libs/qqmap-wx-jssdk');
const db = wx.cloud.database()
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'HUGBZ-6GTKK-WUHJD-AMKI2-AGTX5-35BW4' // 必填
});

Page({
  data: {
    //联想地址列表
    suggestion: [],
    //城市
    city: '',
    //热门城市
    likeCityList: [],
    // 历史记录
    history: []
  },

  //数据回填方法
  backfill: function (e) {
    //获取选中项的相关信息
    const item = this.data.suggestion[e.currentTarget.id]
    // 判断历史记录表中是否有当前选中数据，没有则添加
    this.setHistory(item.city, item.latitude, item.longitude)
    wx.reLaunch({
      url: '/pages/index/index?latitude=' + item.latitude + '&longitude=' + item.longitude + '&city=' + item.city,
    })
  },

  //触发关键词输入提示事件
  getsuggest: function (e) {
   const _this = this;
   //如果输入值长度为0 就关闭联想面板
    if(e.detail.value.length === 0) {
      _this.setData({
        inputVal: '',
        suggestion: [],
      });
    }else{
    //调用关键词提示接口
    qqmapsdk.getSuggestion({
      //获取输入框值并设置keyword参数
      keyword: e.detail.value,
      success: function (res) {
        //搜索成功后的回调
        console.log(res);
        var sug = [];
        for (var i = 0; i < res.data.length; i++) {
          sug.push({
            // 获取返回结果，放到sug数组中
            title: res.data[i].title,
            id: res.data[i].id,
            addr: res.data[i].address,
            city: res.data[i].city,
            district: res.data[i].district,
            latitude: res.data[i].location.lat,
            longitude: res.data[i].location.lng
          });
        }
        _this.setData({
          //设置suggestion属性，将关键词搜索结果以列表形式展示
          inputVal: e.detail.value,
          suggestion: sug,
        });
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  }
  },


  /**
   * 页面载入
   */
  onLoad: function (options) {
    console.log(options)
    this.getLikeCityList();
    let history = wx.getStorageSync('history') || this.data.history
    this.setData({
      location: options.location,
      city: options.city,
      history: history
    })
  },


  /**
   * 搜索输入选择城市
   */
  backfill(src) {
    // console.log(src)
    const city = src.target.dataset.city
    const latitude = src.target.dataset.latitude.toFixed(2)
    const longitude = src.target.dataset.longitude.toFixed(2)
    const type = src.target.dataset.type
    if (latitude, longitude) {
      // 替换激活的样式
      let arr = this.data.history
      //如果点的不是历史记录区域的按钮 则添加到历史记录中
      if (type !== 'history' && type !== 'dingwei') {
        this.setHistory(city, latitude, longitude)
      }
      this.setData({
        activeCity: city,
        history: arr
      })
      db.collection('table').add({
        data: {
          city:city,
          latitude:latitude,
          longitude:longitude,
        }
      })
      .then(res => {
        console.log(res)
      })
      wx.reLaunch({
        url: `/pages/index/index?city=${city}&longitude=${longitude}&latitude=${latitude}`
      })
    } else {
      console.log('点击空白')
    }
  },

  /**
   * 设置历史记录事件
   */
  setHistory: function (city, latitude, longitude) {
    const isHas = this.data.history.some(historyItem => {
      return historyItem.city === city
    })
    //没有数据 在history数组的最前面添加一项
    if (!isHas) {
      let arr = this.data.history
      const obj = {
        city: city,
        latitude: latitude,
        longitude: longitude
      }
      arr.unshift(obj)
      this.setData({
        history: arr
      })
    }
  },

  //取消按钮
  resetValues() {
    wx.reLaunch({
      url: '/pages/index/index',
    })
  },

  /**
   * 猜你想找的城市列表
   */
  getLikeCityList() {
    let likeCityList = [{
        longitude: '116.208660674',
        latitude: '40.002411349',
        city: '北京市'
      },
      {
        longitude: '113.32446',
        latitude: '23.10647',
        city: '广州市'
      },
      {
        longitude: '120.909121124',
        latitude: '31.074282248',
        city: '上海市'
      },
      {
        longitude: '112.98626',
        latitude: '28.25591',
        city: '长沙市'
      },
      {
        longitude: '120.212998446',
        latitude: '30.291330708',
        city: '杭州市'
      },
      {
        longitude: '114.272222573',
        latitude: '30.571999632',
        city: '武汉市'
      },
    ];
    this.setData({
      likeCityList: likeCityList
    })
  },


  //猜你想找
  bindChoose(e) {
    const city = e.currentTarget.dataset.city
    const latitude = e.currentTarget.dataset.latitude
    const longitude = e.currentTarget.dataset.longitude
    const type = e.currentTarget.dataset.type
    if (latitude, longitude) {
      // 替换激活的样式
      let arr = this.data.history
      //如果点的不是历史记录区域的按钮 则添加到历史记录中
      if (type !== 'history' && type !== 'dingwei') {
        this.setHistory(city, latitude, longitude)
      }
      this.setData({
        activeCity: city,
        history: arr
      })
      wx.reLaunch({
        url: `/pages/index/index?city=${city}&longitude=${longitude}&latitude=${latitude}`
      })
    } else {
      console.log('点击空白')
    }
  },


  /**
   * 点击删除按钮
   */
  del() {
    if (this.data.history.length > 0) {
      this.setData({
        history: []
      })
      wx.removeStorageSync('history')
    } else {
      wx.showToast({
        title: '没有要删除的历史记录',
        icon: 'none',
        duration: 1000
      })
    }
  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.setStorageSync('history', this.data.history)
  },

})